<template>
  <div class="home">
    <div v-for="item in todos" :key="item.id">
      Id：{{ item.id }} 名字：{{ item.name }} 状态：<span
        @click="hadleCheck(item)"
        :style="{ color: item.state ? 'green' : 'red' }"
        >{{ item.state ? "√" : "×" }}</span
      >
    </div>
    <div @click="headleAll" :style="{ color: checkall ? 'green' : 'red' }">
      全选{{ checkall ? "√" : "×" }}({{ getLength }})
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
  data() {
    return {
      todos: [
        {
          id: "001",
          name: "吃饭",
          state: true,
        },
        {
          id: "002",
          name: "睡觉",
          state: false,
        },
        {
          id: "003",
          name: "打代码",
          state: true,
        },
        {
          id: "004",
          name: "逛街",
          state: true,
        },
      ],
      checkall: true,
    };
  },
  computed: {
    getLength() {
      return this.todos.filter((item) => item.state).length;
    },
  },
  created() {
    this.checkall = this.todos.every((item) => item.state);
    this.getLength;
  },
  methods: {
    headleAll() {
      // this.checkall = !this.checkall;
      // this.todos = this.todos.map(item => ({...item, state: this.checkall}));
      this.checkall = !this.checkall;
      this.todos.forEach((item) => (item.state = this.checkall));
      this.getLength;
      // if (this.checkall) {
      //   this.todos.forEach((item) => (item.state = false));
      // } else {
      //   this.todos.forEach((item) => (item.state = true));
      // }
      // this.checkall = !this.checkall;
    },

    hadleCheck(item) {
      item.state = !item.state;
      this.checkall = this.todos.every((item) => item.state);
      this.getLength;
    },
  },
};
</script>
